local Lang = require("common.Lang")
local ShopConfig = require("excel.Shop")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local ItemDefine = require("bag.ItemDefine")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local HtmlUtil = require("common.HtmlUtil")
local ShopHelp = require("shop.ShopHelp")
local Log = require("common.Log")
local InnerDataManagerFL = require("innerdata.InnerDataManagerFL")
local InnerDataDefine = require("innerdata.Define")
local Broadcast = require("broadcast.Broadcast")
local HorseLogic = require("horse.HorseLogic")
local PetLogic = require("pet.PetLogic")
local ShenbingLogic = require("shenbing.ShenbingLogic")
local BaowuLogic = require("baowu.BaowuLogic")
local ServerCommonFL = require("serverCommon.ServerCommonFL")
local Util = require("common.Util")
local ArmourLogicFL = require("armour.ArmourLogicFL")

--发送错误信息
function send_err(human, err, a, b, c)
    if not err then
        assert()
    end
    if a then
        err = string.format(err, a, b, c)
    end

    local mm = Msg.gc.GC_SHOP_ERR
    mm.err = err
    Msg.send(mm, human.fd)
end

function getLimitMulti()--human, type)
    --  local multi = VipLogic.getVipTimes(human, VipDefine.VIP_PRIVILEGR_MALLLIMITBUY)
    --  multi = math.floor(multi * 100) / 100
    --  if type > 1 and type <= 6 then
    --    return multi > 0 and multi or 1
    --  end
    return 1
end

--更新单个商城信息
function sendMallInfo(human, mallConfig, index)
    local sendMsg = Msg.gc.GC_MALL_QUERY
    ShopHelp.setGoods(human, sendMsg.goods, mallConfig, index)
    Msg.send(sendMsg, human.fd)
end

--查询商城物品列表
function queryMall(human)
    for j=1, #ShopConfig.mall do
        local mallConfig = ShopConfig[ShopConfig.mall[j].name]
        if not mallConfig then
            return
        end
        sendMallInfo(human, mallConfig, j)
    end
    sendPrivilegeRemainTime(human)
end

--购买道具
function BuyItem(human, mallConfig, itemId, cnt, noDel)
    if mallConfig.type == 1 then
      mallConfig = ShopHelp.getRealPrivilegeConfig()
      mallConfig.type = 1
    end
    for i=1, #mallConfig do
        if mallConfig[i].id == itemId and mallConfig[i].money_type == ItemDefine.ITEM_ID_YUANBAO then
            if mallConfig.type ~= 7 and human.db.shopLimtiCnt[(mallConfig.type - 1) * 60 + i - 1] + cnt > math.floor(mallConfig[i].limitCnt) then
                send_err(human, Lang.SHOP_DJXG_ERR5)
                return false
            elseif mallConfig.type == 7 and human.db.shopLimtiCnt[(mallConfig.type - 1) * 60 + i - 1] + cnt > mallConfig[i].limitCnt then
                send_err(human, Lang.SHOP_DJXG_ERR8)
                return false
            end
            if not ObjHuman.checkYuanbaoEnough(human, mallConfig[i].price * cnt) then
                ShopHelp.onNoRMB(human)
                return false
            end
            if not BagLogic.checkCanAddItem(human, itemId, 1, cnt) then
                send_err(human, Lang.SHOP_ERR_BAG_FULL)
                return false
            end
            if not noDel then
                ObjHuman.decYuanbao(human, mallConfig[i].price * cnt, "shop_buy_item", itemId, cnt)
                send_err(human, Lang.SHOP_BUY_OK, HtmlUtil.fontItemId(itemId, cnt), HtmlUtil.fontYuanbao(mallConfig[i].price * cnt))
                human.db.shopLimtiCnt[(mallConfig.type - 1) * 60 + i - 1] = human.db.shopLimtiCnt[(mallConfig.type - 1) * 60 + i - 1] + cnt
                if mallConfig.type ~= 7 then
                  sendMallInfo(human, mallConfig, mallConfig.type)
                end
                if mallConfig.type == 1 or mallConfig.type == 7 then
                    local grid1 = Grid.create(nil, itemId, cnt, 1)
                    local str = string.format(Lang.SHOP_BUY_BRO, HtmlUtil.fontName(human.name, human._id), HtmlUtil.fontItem(grid1), human._id)
                    Broadcast.sendBroadcast2World(Lang.UP + Lang.GROSSIP, str)
                end
                BagLogic.addItem(human, itemId, 1, cnt, "shop_buy_item")
                Log.write(Log.LOGID_OSS_SHOP_BUY, human._id, human.account, human.name, human.db.lv, mallConfig.type, itemId, cnt, mallConfig[i].price * cnt)
            end
            return true
        elseif mallConfig[i].id == itemId and mallConfig[i].money_type == ItemDefine.ITEM_ID_BIND_YUANBAO then
            if human.db.shopLimtiCnt[(mallConfig.type - 1) * 60 + i - 1] + cnt > math.floor(mallConfig[i].limitCnt) then
                send_err(human, Lang.SHOP_DJXG_ERR5)
                return false
            end
            if ObjHuman.getBindYuanbao(human) < mallConfig[i].price * cnt then
                send_err(human, Lang.SHOP_ERR_BIND_YUANBAO)
                return false
            end
            if not BagLogic.checkCanAddItem(human, itemId, 1, cnt) then
                send_err(human, Lang.SHOP_ERR_BAG_FULL)
                return false
            end
            if not noDel then
                ObjHuman.decBindYuanbao(human, mallConfig[i].price * cnt, "shop_buy_item", itemId, cnt)
                send_err(human, Lang.SHOP_BUY_OK, HtmlUtil.fontItemId(itemId, cnt), HtmlUtil.fontBindYuanbao(mallConfig[i].price * cnt))
                human.db.shopLimtiCnt[(mallConfig.type - 1) * 60 + i - 1] = human.db.shopLimtiCnt[(mallConfig.type - 1) * 60 + i - 1] + cnt
                sendMallInfo(human, mallConfig, mallConfig.type)
                if mallConfig.type == 1 or mallConfig.type == 7 then
                    local grid1 = Grid.create(nil, itemId, cnt, 1)
                    local str = string.format(Lang.SHOP_BUY_BRO, HtmlUtil.fontName(human.name, human._id), HtmlUtil.fontItem(grid1), human._id)
                    Broadcast.sendBroadcast2World(Lang.UP + Lang.GROSSIP, str)
                end
                BagLogic.addItem(human, itemId, 1, cnt, "shop_buy_item")
                Log.write(Log.LOGID_OSS_SHOP_BUY, human._id, human.account, human.name, human.db.lv, mallConfig.type, itemId, cnt, mallConfig[i].price * cnt)
            end
            return true
        end
    end
    return false
end
--快速购买接口
--itemId=道具id， cnt =道具数量， mallId=商城配置表id，不确定不填就可以了
--返回true表示购买成功，返回false表示购买失败，已经处理提示了，不用再额外处理提示,isInMall是否是在商城主页购买，true表示是
function quickBuy(human, itemId, cnt, mallId, isInMall)
    local mallConfig
    if mallId and mallId ~= 0 then
        mallConfig = ShopConfig[ShopConfig.mall[mallId].name]
        mallConfig.type = mallId
        return BuyItem(human, mallConfig, itemId, cnt)
    end
    local config = ShopConfig.mall
    for i=1, #config do
        mallConfig = ShopConfig[ShopConfig.mall[i].name]
        mallConfig.type = i
        if isInMall or (not isInMall and mallConfig[1].money_type ~= ItemDefine.ITEM_ID_YUANBAO) then
          if BuyItem(human, mallConfig, itemId, cnt) then
              return true
          end
        end
    end
    return false
end
--批量购买
--参数itemList = {[1] = {[1] =20001(道具id), [2]=3(道具数量)}, [2] = {[1] =2, [2]=3}}
--返回true表示购买成功，返回false表示购买失败，已经处理提示了，不用再额外处理提示
function batchBuy(human, itemList)
    local config = ShopConfig.mall
    local index = 0
    for i=1, #config do --热销商品不判断
        local mallConfig = ShopConfig[ShopConfig.mall[i].name]
        for j=1, #itemList do
            mallConfig.type = i
            if mallConfig[1].money_type ~= ItemDefine.ITEM_ID_YUANBAO then
              if BuyItem(human, mallConfig, itemList[j][1], itemList[j][2], true) then
                  index = index + 1
              end
            end
        end
        if index == #itemList then
            break
        end
    end
    if #itemList ~= index then
        return false
    else
        for i=1, #config do
            local mallConfig = ShopConfig[ShopConfig.mall[i].name]
            mallConfig.type = i
            if mallConfig[1].money_type ~= ItemDefine.ITEM_ID_YUANBAO then
              for j=1, #itemList do
                  BuyItem(human, mallConfig, itemList[j][1], itemList[j][2])
              end
            end
        end
    end
    return true
end

function sendLimitShowInfo(human)
    local mallConfig = ShopConfig["limitBuy"]
    local sendMsg = Msg.gc.GC_LIMIT_BUY_SHOW_INFO
    local cache = {}
    sendMsg.list[0] = #mallConfig
    for i=1, #mallConfig do
        if mallConfig[i].type == 1 then
            HorseLogic.setHorseShowInfo(sendMsg.list[i], mallConfig[i].useId)
        elseif mallConfig[i].type == 2 then
            PetLogic.setPetShowInfo(sendMsg.list[i], mallConfig[i].useId)
        elseif mallConfig[i].type == 3 then
            ShenbingLogic.setSbShowInfo(sendMsg.list[i], mallConfig[i].useId)
        elseif mallConfig[i].type == 4 then
            BaowuLogic.setBaowuShowInfo(sendMsg.list[i], mallConfig[i].useId)
        else
            ArmourLogicFL.setArmourShowInfo(sendMsg.list[i], mallConfig[i].useId)
        end
        sendMsg.list[i].showPos = mallConfig[i].showPos 
        sendMsg.list[i].getShow = mallConfig[i].getShow
        sendMsg.list[i].skillShow = mallConfig[i].skillShow
        sendMsg.list[i].useShow = mallConfig[i].useShow
    end
    Msg.send(sendMsg, human.fd)
end
--限时购买
function LimitBuy(human, itemId, cnt)
    local mallConfig = ShopConfig["limitBuy"]
    for i=1, #mallConfig do
        if mallConfig[i].id == itemId then
            if ShopHelp.LIMIT_BUY_REMAIN_CNT[i] + cnt > mallConfig[i].maxCnt then
                return send_err(human, Lang.SHOP_DJXG_ERR5)
            end
            mallConfig.type = 7 --限时购买
            if BuyItem(human, mallConfig, itemId, cnt) then
                local info = {}
                info.index = i
                info.cnt = cnt
                InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_SHOP_LIMIT_BUY, info)
--                sendMallInfo(human, mallConfig, 7)
                return true
            end
        end
    end
end

function setCnt(human, oType, info)
    ShopHelp.LIMIT_BUY_REMAIN_CNT = info
    local human1 = ObjHuman.onlineUuid[info.uuid]
    if human1 then
        sendMallInfo(human1, ShopConfig["limitBuy"], 7)        
    end
end

function clearStatus(human)
    if ServerCommonFL.getHadOpenDay() % 2 == 1 or Util.diffDay(human.db.update_daily_time) >= 2 then
      for i=0, 59 do
        human.db.shopLimtiCnt[i] = 0
      end
    end
    for i=0, ShopHelp.SHOP_LIMIT_BUY_MAX_CNT - 1 do
        if math.floor(i/60) ~= 0 and math.floor(i/60) ~= 6 then
            human.db.shopLimtiCnt[i] = 0
        end
    end
    queryMall(human)
end

function sendPrivilegeRemainTime(human)
  local sendMsg = Msg.gc.GC_PRIVILEGE_REFRESH_REMAIN_TIME
  local remainDay = ServerCommonFL.getHadOpenDay() % 2
  sendMsg.remainTime = Util.remainDaySeconds() + (86400 * remainDay)
  Msg.send(sendMsg, human.fd)
end

InnerDataManagerFL.Register(InnerDataDefine.INNERDATA_TYPE_SHOP_LIMIT_BUY, setCnt)
